package com.darchrow.nio.file;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;

/**
 * @author mdl
 * @date 2020/5/27 17:35
 */
public class CharCoderTest {
    public static void main(String[] args) throws Exception {
        Charset charset = null;
        CharsetDecoder decoder = null;
        String charsetName = "UTF-8";
        int capacity = 10;

        charset = Charset.forName(charsetName);
        decoder = charset.newDecoder();

        String s ="客户端发送dsad德生科技电脑fdas上考虑迪士尼年少弗拉门发生ofjam打什么的即破发麦克 ‘；打， 饭哦按都";
        byte[] bytes = s.getBytes(charsetName);

        //模拟接收的ByteBuffer   size 10
        ByteBuffer byteBuffer = ByteBuffer.allocate(capacity);
        //用于临时存放Bytebuffer转换后的字符
        CharBuffer charBuffer = CharBuffer.allocate(capacity);
        //用于连接展示字符串
        StringBuilder sb = new StringBuilder();

        int i = 0;
        while(true){
            byteBuffer.put(bytes[i]);
            i++;
            if(byteBuffer.remaining()==0||i==bytes.length){
                byteBuffer.flip();
                CoderResult coderResult;
                if(i!=bytes.length){
                    coderResult = decoder.decode(byteBuffer,charBuffer,false);
                }else{
                    coderResult = decoder.decode(byteBuffer,charBuffer,true);
                }
                //有错误
                if(coderResult.isError()){
                    coderResult.throwException();
                }
                charBuffer.flip();
                sb.append(charBuffer);
                charBuffer.clear();
                byteBuffer.compact();
            }
            //退出循环
            if(i == bytes.length){
                break;
            }
        }
        System.out.println(sb);
    }
}
